<!-- src/views/realTime.vue -->
<template>
  <a-card title="实时缺陷检测">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-form layout="vertical">
          <a-form-item label="摄像头ID">
            <a-input-number v-model:value="cameraId" :min="0" />
          </a-form-item>
          <a-form-item label="存储间隔(秒)">
            <a-input-number v-model:value="storageInterval" :min="1" />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              @click="startDetection"
              :loading="loading"
              :disabled="isRunning"
            >
              开始检测
            </a-button>
            <a-button
              type="danger"
              @click="stopDetection"
              :loading="loading"
              :disabled="!isRunning"
              style="margin-left: 10px"
            >
              停止检测
            </a-button>
          </a-form-item>
        </a-form>
      </a-col>
      <a-col :span="18">
        <div v-if="currentImage && isRunning" class="image-container">
          <img :src="currentImage" alt="实时检测画面" style="max-width: 100%" @error="onImageError" />
          <div class="results-panel">
            <h3>检测结果:</h3>
            <a-list :data-source="formattedResults" item-layout="horizontal">
              <template #renderItem="{ item }">
                <a-list-item>
                  <span>{{ item.label }} (置信度: {{ item.confidence }}%)</span>
                  <span style="margin-left: 10px">位置: [{{ item.bbox.join(', ') }}]</span>
                </a-list-item>
              </template>
            </a-list>
          </div>
        </div>
        <div v-else class="empty-state">
          <a-empty :description="wsStatus" />
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, onActivated, onDeactivated } from 'vue';
import { message } from 'ant-design-vue';
import WebSocketClient from '@/utils/websocket';
import { startCameraUsingPost, stopCameraUsingPost } from '@/api/cameraController.ts';

const WS_BACKEND_URL = 'ws://localhost:8090/live'; // 确保与后端一致

const defectMap = {
  'Crazing': '裂纹',
  'inclusion': '夹杂物',
  'Patches': '斑点',
  'Pitted Surface': '麻面',
  'Rolled-in Scale': '轧入氧化皮',
  'Scratches': '划痕'
};

const cameraId = ref(1);
const storageInterval = ref(5);
const loading = ref(false);
const isRunning = ref(false);
const currentImage = ref(null);
const currentResults = ref([]);
const wsStatus = ref('等待连接...');
let wsClient = null;

const formattedResults = computed(() => {
  return currentResults.value.map(result => ({
    label: defectMap[result.className] || result.className,
    confidence: Math.round(result.confidence * 100),
    bbox: result.bbox.map(coord => Math.round(coord))
  }));
});

const startDetection = async () => {

  connectWebSocket();
  try {
    loading.value = true;
    const response = await startCameraUsingPost({ cameraId: cameraId.value, storageInterval: storageInterval.value });
    if (response.data && response.data.status === 'success') {
      isRunning.value = true;
      message.success('检测已开始');
      console.log('开始检测，isRunning:', isRunning.value);
    } else {
      message.error('启动检测返回异常');
    }
  } catch (error) {
    console.error('启动检测错误:', error);
    message.error(`启动检测失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

const stopDetection = async () => {
  try {
    loading.value = true;
    const response = await stopCameraUsingPost({ cameraId: cameraId.value });

    if (response.data && response.data.status === 'success') {
      isRunning.value = false;
      currentImage.value = null;
      currentResults.value = [];
      message.success('检测已停止');
      console.log('停止检测，isRunning:', isRunning.value);
    } else {
      message.error('停止失败，请检查摄像头ID');
    }
  } catch (error) {
    console.error('停止检测错误:', error);
    message.error(`停止检测失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

const handleMessage = (data) => {
  console.log('收到 WebSocket 数据:', data);
  if (data.cameraId === cameraId.value && isRunning.value) { // 只有运行时才更新
    if (data.image) {
      currentImage.value = data.image;
      console.log('图片数据长度:', data.image.length);
    } else {
      console.warn('收到消息中无图片数据');
    }
    currentResults.value = data.results || [];
  } else {
    console.log('忽略数据，当前未运行或 cameraId 不匹配');
  }
};

const onImageError = () => {
  console.error('图片加载失败');
  message.error('图片显示失败，可能格式错误');
  currentImage.value = null;
};
const connectWebSocket = () => {
  console.log('组件挂载');
  const wsUrl = WS_BACKEND_URL;
  console.log('尝试连接 WebSocket:', wsUrl);

  wsClient = new WebSocketClient(wsUrl);
  wsClient.connect();
  wsClient.addListener('realTime', handleMessage);

  wsClient.ws.onopen = () => {
    wsStatus.value = '等待检测开始...';
    message.success('WebSocket 连接成功');
    console.log('WebSocket 已连接');
  };

  wsClient.ws.onerror = (error) => {
    wsStatus.value = 'WebSocket 连接错误';
    console.error('WebSocket 错误:', error);
    message.error('WebSocket 连接失败');
  };

  wsClient.ws.onclose = () => {
    wsStatus.value = 'WebSocket 连接已关闭';
    console.log('WebSocket 已关闭');
    message.warning('WebSocket 连接断开');
  };
}
onMounted(() => {
  // connectWebSocket();
});

onActivated(() => {
  console.log('组件激活（切换回来）, isRunning:', isRunning.value);
  // 切换回来时不自动开始，只保持状态
});

onDeactivated(() => {
  console.log('组件失活（切换走）, isRunning:', isRunning.value);
  // 可选择在此暂停显示，但保留连接
});

onUnmounted(() => {
  console.log('组件卸载');
  if (wsClient) {
    wsClient.removeListener('realTime');
    wsClient.disconnect();
  }
});
</script>

<style scoped>
.image-container {
  position: relative;
}

.results-panel {
  margin-top: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
}
</style>
